//
//  DKShortVideoListCell.m
//  DKShortVideo
//
//  Created by Keer_LGQ on 2018/3/30.
//  Copyright © 2018年 DK. All rights reserved.
//

#import "DKShortVideoListCell.h"
#import "UIImageView+WebCache.h"
#import "Masonry.h"
#import "OpenGLPixelBufferView.h"

@interface DKShortVideoListCell ()
{
    OpenGLPixelBufferView *_previewView;
    BOOL _addedObservers;
    BOOL _allowedToUseGPU;
    
    CGFloat _position;
    CADisplayLink *_link;
}
@property UIImageView *thumb;
@property UILabel *durationLabel;
@property UILabel *title;

@end

@implementation DKShortVideoListCell
{
    ListVideoModel *_source;
}

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        
        self.backgroundColor = [UIColor clearColor];
        
        self.thumb = [[UIImageView alloc] initWithFrame:CGRectZero];
        [self addSubview:self.thumb];
        [self.thumb mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(120, 68));
            make.centerY.mas_equalTo(self.mas_centerY);
            make.left.mas_equalTo(15);
        }];
        
        self.durationLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        self.durationLabel.font = [UIFont systemFontOfSize:12];
        self.durationLabel.textColor = [UIColor whiteColor];
        [self.thumb addSubview:self.durationLabel];
        [self.durationLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self.thumb.mas_right).offset(-7);
            make.bottom.equalTo(self.thumb.mas_bottom).offset(-7);
        }];
        
        self.title = [[UILabel alloc] initWithFrame:CGRectZero];
        self.title.font = [UIFont systemFontOfSize:14];
        self.title.textColor = [UIColor whiteColor];
        [self addSubview:self.title];
        [self.title mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.thumb.mas_right).offset(20);
            make.right.equalTo(self.mas_right).offset(20);
            make.height.mas_equalTo(68);
            make.centerY.mas_equalTo(self.mas_centerY);
        }];
        
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        
        [self setupPreviewView];
        [self configNotification];
        _position = 0;
        
        _link = [CADisplayLink displayLinkWithTarget:self selector:@selector(renderVideo)];
        [_link addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
        [_link setPaused:YES];
    }
    return self;
}

- (void)setDataSource:(ListVideoModel *)source;
{
    _source = source;
    
    int duration = source.duration;
    [self.thumb sd_setImageWithURL:[NSURL URLWithString:_source.cover]
                  placeholderImage:nil];
    self.durationLabel.text = [NSString stringWithFormat:@"%02d:%02d", duration / 60, duration % 60];
    self.title.text = source.title;
}

- (ListVideoModel *)getSource;
{
    return _source;
}

- (void)configNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(applicationDidEnterBackground)
                                                 name:UIApplicationDidEnterBackgroundNotification
                                               object:[UIApplication sharedApplication]];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(applicationWillEnterForeground)
                                                 name:UIApplicationWillEnterForegroundNotification
                                               object:[UIApplication sharedApplication]];
    _addedObservers = YES;
    
    _allowedToUseGPU = ( [UIApplication sharedApplication].applicationState != UIApplicationStateBackground );

}

- (void)dealloc
{
    if ( _addedObservers ){
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:[UIApplication sharedApplication]];
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillEnterForegroundNotification object:[UIApplication sharedApplication]];
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:[UIDevice currentDevice]];
        [[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];
    }
}


#pragma mark preview video
- (void)renderVideo
{
    NSString *fullPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"banana.jpg"];
    UIImage *image = [UIImage imageWithContentsOfFile:fullPath];
    
    CVPixelBufferRef pixelBuffer = [self ConvertToCVPixelBufferRefFromImage:image.CGImage withSize:image.size];

//    pixelBuffer = [_player getLastestSampleBuffer];
    
    dispatch_async( dispatch_get_main_queue(), ^{
        @autoreleasepool {

            @synchronized( self )
            {
                if (pixelBuffer != NULL) {
                    [_previewView displayPixelBuffer:pixelBuffer];
                }

            }
        }
    } );
}

- (void)setupPreviewView
{
    // Set up GL view
    _previewView = [[OpenGLPixelBufferView alloc] initWithFrame:CGRectZero];
    _previewView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    
    [self.contentView addSubview:_previewView];
    CGRect bounds = CGRectZero;
    bounds.size = [self.contentView convertRect:self.contentView.bounds toView:_previewView].size;
    _previewView.bounds = bounds;
    _previewView.center = CGPointMake( self.contentView.bounds.size.width/2.0, self.contentView.bounds.size.height/2.0 );
}

- (void)applicationDidEnterBackground
{
    // Avoid using the GPU in the background
    _allowedToUseGPU = NO;
    [_link setPaused:YES];

    // We reset the OpenGLPixelBufferView to ensure all resources have been cleared when going to the background.
    [_previewView reset];
}

- (void)applicationWillEnterForeground
{
    _allowedToUseGPU = YES;
    [_link setPaused:NO];
}

- (void)previewAction
{
    if ( ! _allowedToUseGPU ) {
        return;
    }
    
    if ( ! _previewView ) {
        [self setupPreviewView];
    }
    [_link setPaused:NO];
}

- (void)stopPreview
{
    [_previewView reset];
    [_link setPaused:YES];
}

-(CVPixelBufferRef)ConvertToCVPixelBufferRefFromImage: (CGImageRef )image withSize:(CGSize) size {
    NSDictionary *options =[NSDictionary dictionaryWithObjectsAndKeys:
                            [NSNumber numberWithBool:YES],kCVPixelBufferCGImageCompatibilityKey,
                            [NSNumber numberWithBool:YES],kCVPixelBufferCGBitmapContextCompatibilityKey,nil];
    
    CVPixelBufferRef pxbuffer =NULL;
    CVReturn status =CVPixelBufferCreate(kCFAllocatorDefault,size.width,size.height,kCVPixelFormatType_32BGRA,(__bridge CFDictionaryRef) options,&pxbuffer);
    
    NSParameterAssert(status ==kCVReturnSuccess && pxbuffer !=NULL);
    
    CVPixelBufferLockBaseAddress(pxbuffer,0);
    void *pxdata =CVPixelBufferGetBaseAddress(pxbuffer);
    NSParameterAssert(pxdata !=NULL);
    
    CGColorSpaceRef rgbColorSpace=CGColorSpaceCreateDeviceRGB();
    CGContextRef context =CGBitmapContextCreate(pxdata,size.width,size.height,8,4*size.width,rgbColorSpace,kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Little);
    NSParameterAssert(context);
    
    
    CGContextDrawImage(context,CGRectMake(0,0,CGImageGetWidth(image),CGImageGetHeight(image)),image);
    CGColorSpaceRelease(rgbColorSpace);
    CGContextRelease(context);
    
    CVPixelBufferUnlockBaseAddress(pxbuffer,0);
    
    
    return pxbuffer;
}
@end

@implementation ListVideoModel

@end
